<template>
    <div class="issues">
        <!--issue-step modal start-->
        <modal id="issue-step" :show.sync="showIssueStepModal" :dialogCSS="{'width': '70%'}" @cancel=" currentIssue = null">
            <template slot="header"></template>
            <template slot="body">
                <issue-step v-if="currentIssue" :title="currentIssue.summary" :loading="showIssueStep"
                            :desc="currentIssue.message" :steps="steps" :id="currentIssue.id" :done="currentIssue.hidden" :destory="!showIssueStepModal"></issue-step>
            </template>
            <template slot="footer">
                <div></div>
            </template>
        </modal>
        <!--issue-step modal end-->
        <!--issue modal start-->
        <modal :show.sync="showIssuesModal" id="issues-modal">
            <template slot="header"></template>
            <template slot="body">
                <div>
                    <div class="form-group">
                        <label for="">Category</label>
                        <input class="form-control" :value="currentType" type="text" disabled>
                    </div>
                    <div class="form-group">
                        <label for="">Type Code
                            <i  v-tooltip.top="`Get Issue Tip`" class="fif fif-tip text-info" style="cursor: pointer;" @click="getIssueTip(issue.type_code)"></i>
                        </label>
                        <menu-select :init="showIssuesModal" v-model="issue.type_code"></menu-select>
                    </div>
                    <div class="form-group">
                        <label for="">Title <i class="text-danger">*</i></label>
                        <input v-model="issue.summary" type="text" class="form-control" placeholder="Title"></div>
                    <div class="form-group">
                        <label for="">Content <i class="text-danger">*</i></label>
                        <textarea rows="10" v-model="issue.message" class="form-control"></textarea>
                    </div>
                </div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger waves-effect waves-light" @click="addIssue">Submit</button>
            </template>
        </modal>
        <!--issue modal end-->
        <!--chat html modal start-->
        <modal :show.sync="showHtmlModal" id="html-modal">
            <template slot="body">
                <div style="height: 600px;" id="iframe-wrapper"></div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
            </template>
        </modal>
        <!--chat html modal end-->
        <div class="row">
            <div class="col-md-12">
                <div class="white-box" style="padding: 0;overflow: auto;">
                    <div class="vtabs" style="width: 100%;">
                        <!--left issue list  start-->
                        <ul class="nav tabs-vertical">
                            <li :key="'issueType' + index" class="tab" v-for="(type, index) in $store.state.issuesType"
                                :class="{'active': type.toLowerCase() == currentType.toLowerCase()}"
                                @click="currentType = type">
                                <a data-toggle="tab" href="#" aria-expanded="true">
                                    <span class="visible-xs"></span><span class="hidden-xs">{{type}}</span> </a>
                            </li>
                        </ul>
                        <!--left issue list  end-->
                        <!--right issue table  start-->
                        <div class="tab-content" style="width: 100%;">
                            <item-table :columns="columns" :data="data" :total="total" :loading="tableLoading"
                                        @sort="sort"
                                        isAdd @add="toShowIssueModal" @filter="_filterFromLabel" :responsive="false"
                            >
                                <template slot="type_code" slot-scope="props">
                                    {{props.item.type_code}}
                                    <i v-if="props.item.type_code" v-tooltip.top="`Get Issue Tip`" class="fif fif-tip text-info" style="cursor: pointer;" @click="getIssueTip(props.item.type_code)"></i>
                                </template>
                                <template slot="actions" slot-scope="props">
                                    <button  v-if="props.item.hidden" type="button"
                                             class="btn btn-danger btn-outline btn-circle btn-md m-r-5" v-tooltip.top="`Mark as Unresolved`"
                                             @click="done(props, 'undone', 'Mark as Unresolved?')">
                                        <i class="fif fif-undone"></i>
                                    </button>
                                    <button  v-else type="button"
                                             class="btn btn-success btn-outline btn-circle btn-md m-r-5" v-tooltip.top="`Mark as Resolved`"
                                             @click="done(props, 'done', 'Mark as Resolved?')">
                                        <i class="fif fif-done"></i>
                                    </button>
                                    <button  type="button" v-if="!props.item.hidden"
                                             class="btn btn-primary btn-outline btn-circle btn-md m-r-5" v-tooltip.top="`Add Comment`"
                                             @click="addComment(props)">
                                        <i class="fif fif-add-remark"></i>
                                    </button>
                                    <button  type="button"
                                             class="btn btn-info btn-outline btn-circle btn-md m-r-5" v-tooltip.top="`Details`"
                                             @click.stop="getIssueStep(props)">
                                        <i class="fif fif-process"></i>
                                    </button>
                                </template>
                                <template slot="type" slot-scope="props">
                                    <select v-if="!props.item.hidden" @change="onSelectType($event, props)" class="form-control"
                                            style="width: 120px;" v-model="props.item.type" ref="status">
                                        <option  :key="'issueType' + index"  :value="type" v-for="(type, index) in $store.state.issuesType">{{type}}</option>
                                    </select>
                                    <span v-else>{{props.item.type}}</span>
                                </template>
                                <template slot="current_group" slot-scope="props">
                                    <select v-if="!props.item.hidden" @change="onSelectGroup($event, props)" class="form-control"
                                            style="width: 120px;" v-model="props.item.current_group_id" ref="status">
                                        <option selected v-show="false"></option>
                                        <option :key="'group' + index"  :value="group.value" v-for="(group, index) in groups">{{group.label}}</option>
                                    </select>
                                    <span v-else>{{props.item.current_group}}</span>
                                </template>
                                <template slot="message" slot-scope="props">
                                    <div class="td-ellipsis">
                                        {{props.item.message}}
                                    </div>
                                    <i class="fif fif-ellipsis text-info"
                                       @click="showMessageDetail(props.item.id, props.item.message)"></i>
                                </template>
                                <template slot="summary" slot-scope="props">
                                    <div class="td-ellipsis">
                                        {{props.item.summary}}
                                    </div>
                                    <i class="fif fif-ellipsis text-info"
                                       @click="showMessageDetail(props.item.id, props.item.summary)"></i>
                                </template>
                                <template slot="related_chat" slot-scope="props">
                                    <a v-if="props.item.related_message" class="btn btn-info btn-xs"
                                       @click="toShowHtml(props.item.related_message)"
                                       target="_blank">
                                        Message
                                    </a>
                                    <a v-if="props.item.related_chat" class="btn btn-primary btn-xs"
                                       :href="`#/chat/all?search=${props.item.related_chat}&type=Number`"
                                       target="_blank">
                                        Chat
                                    </a>
                                </template>
                                <template slot="hidden" slot-scope="props">
                                    <span class="label label-success" v-if="props.item.hidden">Resolved</span>
                                    <span class="label label-danger" v-else>Unresolved</span>
                                </template>
                                <template slot="current_status" slot-scope="props">
                                    <select v-if="!props.item.hidden" @change="onSelect($event, props)" class="form-control"
                                            style="width: 120px;" v-model="props.item.current_status" ref="status">
                                        <option selected v-show="false"></option>
                                        <option :key="'option' + index"  :value="option.value" v-for="(option, index) in genOption(props)">
                                            {{option.label}}
                                        </option>
                                    </select>
                                    <span v-else>{{props.item.current_status}}</span>
                                </template>
                            </item-table>
                            <v-paginate :pageCount="pageCount" :page="page" @change="changePage"></v-paginate>
                        </div>
                        <!--right issue table  end-->
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

    import ItemTable from '@/components/widgets/ItemTable'
    import vPaginate from '@/components/widgets/Pagination'
    import MenuSelect from '@/components/widgets/MenuSelect'
    import IssueStep from '@/components/widgets/IssueStep'
    import Modal from '@/components/widgets/Modal'
    import {updateModel, searchModel, addModel} from "@/api/model";
    import swal from 'sweetalert'
    import columns from '@/config/columns'
    import config from '@/config'

    export default {
        name: "Issues",
        components: {ItemTable, vPaginate, Modal, MenuSelect, IssueStep},
        created() {
            this.model = 'Issues'
            this.columns = columns[this.model]
            this.currentType = this.$route.params.type
            this.groups = config.GROUPS
        },
        data() {
            return {
                tableLoading: false,
                opt: {
                    hidden: 0,
                },
                page: 1,
                pageCount: 0,
                total: 0,
                type: '',
                orderBy: '-gen_time',
                data: [],
                currentType: '',
                showHtmlModal: false,
                currentMsg: null,

                source: null,

                showIssuesModal: false,
                issue: {
                    summary: '',
                    message: '',
                    type_code: ''
                },

                showTransfer: false,

                currentIssue: null,
                showIssueStep: false,
                showIssueStepModal: false,
                steps: []
            }
        },
        methods: {
            sort(dir, column) {
                dir = dir[0]
                column = column[0]
                this.orderBy = dir === 'descend' ? '-' + column : column
                this.fetch()
            },
            // 获取左侧issue所有类型
            _filterFromLabel(column) {
                this.opt = this.opt || {}
                let key = column.filterKey ? column.filterKey : column.key
                let isAll = true
                for (let i = 0; i < column.filterSelect.length; i++) {
                    if (column.filterSelect[i].selected) {
                        this.opt[key] = column.filterSelect[i].value
                    } else {
                        isAll = false
                    }
                }

                if (isAll && this.opt.hasOwnProperty(key)) {
                    delete this.opt[key]
                }

                this.fetch()
            },
            fetch() {
                this.tableLoading = true
                this.data = []
                this.opt['type'] = this.currentType
                searchModel(this.model, {
                    page: this.page,
                    order_by: this.orderBy,
                    search_keys: this.opt,
                }, this.source).then(response => {
                    this.tableLoading = false
                    this.page = response.data.page.number
                    this.pageCount = response.data.page.range
                    this.total = response.data.page.total
                    this.data = response.data.list

                    this.$nextTick(() => {
                        let scroll = document.documentElement || document.body
                        let scrollTop = scroll.scrollTop
                        scroll.scrollTop = scrollTop
                    })

                }).catch(e => {
                    this.tableLoading = false
                    this.data = []
                })
            },
            genOption(props) {
                return [
                    {label: 'Pending', value: 'Pending'},
                    {label: 'In_Progress', value: "In_Progress"},
                    {label: 'Resolved', value: "Resolved"},
                ]
            },
            // 当Status下拉选择回调
            onSelect(ele, props, type) {
                let attr = {
                    current_status: props.item.current_status
                }
                this.tableLoading = true
                updateModel(this.model, props.item.id, attr).then(res => {
                    this.tableLoading = false
                    swal("success", "", "success")
                    this.fetch()
                }).catch(e => {
                    this.tableLoading = false
                })
            },
            // 当Category下拉选择回调
            onSelectType(ele, props, type) {
                let attr = {
                    type: props.item.type
                }
                this.tableLoading = true

                if (props.item.id) {
                    swal({
                        title: "Are you sure?",
                        text: `move this item to ${props.item.type}`,
                        icon: "warning",
                        dangerMode: true,
                        buttons: true,
                    }).then((willDelete) => {
                        if (willDelete) {
                            updateModel(this.model, props.item.id, attr).then(res => {
                                this.tableLoading = false
                                swal("success", "", "success")
                                this.fetch()
                            }).catch(e => {
                                this.tableLoading = false
                            })
                        } else {
                            this.fetch()
                        }
                    })
                }
            },
            // 显示related chat modal
            toShowHtml(msg) {
                this.showHtmlModal = true
                this.currentMsg = msg
                let wrapper = $("#iframe-wrapper")
                let iframe = $(' <iframe id="message-html" frameborder="0"\n' +
                    '                            style=" width: 100%; height: 100%; ">\n' +
                    '                    </iframe>')
                wrapper.html(iframe)
                // let iwindow = iframe.contentWindow
                iframe.contents().find('body').html(this.formatHTML(msg))
            },
            // 去除related chat html中script,style标签
            formatHTML(html) {
                return html ? html
                        .replace(/<style[^>]*>/g, '<div style="display: none;">').replace(/<\/style>/g, '</div>')
                        .replace(/<script[^>]*>/g, '<div style="display: none;">').replace(/<\/script>/g, '</div>')
                    : ''
            },
            showMessageDetail(id, msg) {
                swal('', msg, 'info')
            },
            // 根据type标记已解决/未解决
            done(props, type, title) {
                if (props.item.id) {

                    let textarea = document.createElement("textarea");
                    textarea.rows = "4"
                    textarea.className = "form-control"
                    textarea.value = ""

                    swal({
                        title: title,
                        content: textarea,
                        icon: 'warning',
                        buttons: true,
                    }).then((will) => {
                        if (will) {
                            if (!textarea.value.trim().length) {
                                return $.toast({
                                    heading: 'Please Type Something',
                                    position: 'top-right',
                                    loaderBg: '#ff6849',
                                    icon: 'error',
                                })
                            }
                            let attr = {
                                resolved_by_user: type === 'done' ? this.$store.state.user : null,
                                hidden: type === 'done' ? true : false,
                                current_status: type === 'done' ? 'Resolved' : '',
                                // message: `${props.item.message};${textarea.value}`
                            }
                            this.tableLoading = true
                            updateModel(this.model, props.item.id, attr).then(res => {
                                this.$store.dispatch("setIssueNum")
                                addModel("IssueComment", {
                                    text: textarea.value,
                                    author: this.$store.state.user,
                                    issue: props.item.id
                                }).then(res => {
                                    this.tableLoading = false
                                    this.fetch()
                                    $.toast({
                                        heading: 'success',
                                        position: 'top-center',
                                        icon: 'success',
                                    });
                                })

                            }).catch(e => {
                                this.tableLoading = false
                            })
                        }
                    })
                }
            },
            // 点击分页回调
            changePage(page) {
                this.page = page
                this.fetch()
            },
            /**
             * 添加issue
             */
            toShowIssueModal() {
                this.showIssuesModal = true
                this.issue.message = ''
                this.issue.summary = ''
                this.issue.type_code = ''
            },
            addIssue() {
                if (!this.issue.message.trim().length ||!this.issue.summary.trim().length) {
                    return $.toast({
                        heading: 'Wrong',
                        text: 'You must fill fields with *',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error'
                    });
                }

                let currentGroup = null
                this.groups.forEach(item => {
                    if (this.$store.state.groups.indexOf(item.value) !== -1) {
                        currentGroup = item.value
                    }
                })

                let params = {
                    type: this.currentType,
                    message: this.issue.message,
                    summary: this.issue.summary,
                    created_by_user: this.$store.state.user,
                    type_code: this.issue.type_code,
                    current_group: currentGroup,
                    current_user: this.$store.state.user
                }

                if (!currentGroup) delete params.current_group

                addModel(this.model, params).then(() => {
                    swal("success", "", "success")
                    this.showIssuesModal = false
                    this.fetch()
                    this.$store.dispatch("setIssueNum")
                }).catch(e => {
                    this.tableLoading = false
                })
            },
            /**
             * 获取issue对应的解决方案
             * @param code
             * @returns {{reset, update, close}|{reset, update}}
             */
            getIssueTip(code) {
                if (!code.trim().length) {
                    return $.toast({
                        heading: 'Wrong',
                        text: '输入CASE CODE',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error'
                    });
                }

                searchModel('IssueReccomendation', {
                    page: 1,
                    search_keys: {
                        type_code: code
                    }
                }, null).then(res => {
                    if (res.data.list.length) {
                        swal('', res.data.list[0].recommendation, 'info')
                    } else {
                        $.toast({
                            heading: 'Wrong',
                            text: 'Not matched case',
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error'
                        });
                    }
                })
            },
            /**
             * 获取分组对应名称
             * @param current_group_id
             * @returns {string}
             * @private
             */
            _getGroupLabel(current_group_id) {
                let newGroup = ''
                this.groups.forEach(item => {
                    if (item.value == current_group_id) newGroup = item.label
                })
                return newGroup
            },
            // 当Department下拉选择回调
            onSelectGroup(ele, props) {
                let textarea = document.createElement("textarea");
                textarea.className = 'form-control'
                textarea.rows = "4"
                let newGroup = this._getGroupLabel(props.item.current_group_id)

                swal({
                    title: `Transfer this issue to ${newGroup}？`,
                    content: textarea,
                    icon: 'warning',
                    buttons: true,
                }).then((will) => {
                    if (will) {
                        if (!textarea.value.trim().length) {
                            this.fetch()
                            return $.toast({
                                heading: 'Please Type Something',
                                position: 'top-right',
                                loaderBg: '#ff6849',
                                icon: 'error',
                            })
                        }
                        let attr = {
                            current_group: parseInt(props.item.current_group_id),
                            current_user: this.$store.state.user
                        }
                        this.tableLoading = true
                        updateModel(this.model, props.item.id, attr).then(() => {
                            addModel("IssueComment", {
                                text: textarea.value,
                                author: this.$store.state.user,
                                issue: props.item.id
                            }).then(res => {
                                this.tableLoading = false
                                $.toast({
                                    heading: 'success',
                                    position: 'top-center',
                                    icon: 'success',
                                });
                            })
                        }).catch(e => {
                            this.tableLoading = false
                            this.fetch()
                        })
                    }
                    else {
                        this.fetch()
                    }
                })
            },
            // 点击add comment 回调
            addComment(props) {
                let textarea = document.createElement("textarea");
                textarea.rows = "4"
                textarea.className = "form-control reply-template"
                textarea.value = ""
                swal({
                    content: textarea,
                    icon: 'info',
                    button: {
                        text: "Add",
                        closeModal: true,
                    },
                }).then((value) => {
                    if (value && textarea.value.length) {
                        this.tableLoading = true
                        addModel("IssueComment", {
                            text: textarea.value,
                            author: this.$store.state.user,
                            issue: props.item.id
                        }).then(res => {
                            this.tableLoading = false
                            this.fetch()
                            $.toast({
                                heading: 'success',
                                position: 'top-center',
                                icon: 'success',
                            });
                        }).catch(e => {
                            this.tableLoading = false
                        })
                    }

                })
            },
            /**
             * 获取issue-step，并根据step-order设置step顺序；
             * step-comments根据step时间来确定是哪个step的comment
             * @param props
             */
            getIssueStep(props) {
                this.currentIssue = props.item
                this.showIssueStepModal = true
                this.showIssueStep = true
                searchModel('IssueStep', {
                    page: 1,
                    search_keys: {
                        issue_id: props.item.id
                    }
                }, null).then(res => {
                    let firstStep = null
                    let tmp = []
                    this.steps = []
                    for (let i = 0; i < res.data.list.length; i++) {
                        if (!res.data.list[i].parent) {
                            firstStep = res.data.list[i]
                            tmp.push(firstStep)
                        }
                        res.data.list[i].groupLabel = this._getGroupLabel(res.data.list[i].group)
                    }

                    if (firstStep) {
                        tmp = tmp.concat(this._stepOrder(firstStep, res.data.list))
                    }

                    searchModel('IssueComment', {
                        page: 1,
                        search_keys: {
                            issue_id: props.item.id
                        }
                    }, null).then( (res) => {
                        tmp.forEach( (item, index) => {
                            let start = item.date
                            let end = index >= tmp.length - 1 ? null : tmp[ index + 1 ].date
                            tmp[index].comments = this._getComments(start, end, res.data.list)
                        })
                        this.steps = tmp
                        this.showIssueStep = false
                    } )

                }).catch(e => {
                    this.showIssueStep = false
                })
            },
            _getComments(start, end ,comments) {
                let result = []
                comments.forEach( item => {
                    if (end) {
                        if (item.date >= start && item.date < end) result.push(item)
                    } else {
                        if (item.date >= start) result.push(item)
                    }
                } )
                return result
            },
            _stepOrder(firstStep, steps) {
                let child = firstStep.child
                let tmp = []
                while (child) {
                    let tmpChild = null
                    for (let i = 0; i < steps.length; i++) {
                        if (child == steps[i].id) {
                            tmp.push(steps[i])
                            tmpChild = steps[i].child
                        }
                    }
                    child = tmpChild
                }
                return tmp
            }
        },
        watch: {
            '$route'() {
                if (this.$route.params.type) {
                    this.currentType = this.$route.params.type
                }
            },
            currentType() {
                this.$router.push(`/issues/${this.currentType}`)
                this.$store.state.cancelToken && this.$store.state.cancelToken.cancel()
                this.fetch()
            }
        }
    }
</script>

<style scoped lang="stylus">
    .issue-step-wrapper
        position : absolute
        left: 0
        right: 0
        top: 0
        bottom: 0
        //background-color: #000;
        //opacity: .75
        z-index: 998
        .issue-step
            opacity: 1
            position : absolute;
            left: 10%
            right: 10%
            top: 20%
            z-index: 999
</style>